<?php

/**
 * 推送订单结算数据服务
 */
namespace App\Service\AppService;
use App\Service\BaseService;
use App\Model\PssModel\OrderSupplier;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Amqp\Producer;
use App\Amqp\Producer\HglycSettleMentProducer;
use Throwable;
use App\Service\Code\Normal;
use App\Model\CommodityModel\WarehouseInfo;
use App\Model\PssModel\OrderSettlementMiddle;
use Service\AppService\IdService;

class PushOrderSettleMentService extends BaseService
{
    public $goodsType = [
        0 => '一般贸易',
        1 => '保税品',
        2 => '海外直邮'
    ];
    
    const SETTLEMENT_MODE_PAY           = 1;//支付
    const SETTLEMENT_MODE_AFTER_SALE    = 2;//售后
    
    /**
     * 写入结算数据临时表
     * @param array $param
     */
    public function addOrderSettleMentLog( $param = [] ) 
    {
        $orderInfo          = $param['supplierOrder'];
        $mode               = $param['mode'];
        $binfo              = $param['binfo'];
        $order_id           = $orderInfo['id'];
        $order_type         = $mode;
        $insert = [
            'id'            => IdService::instance()->getOtherID(),
            'bid'           => $binfo['bid'],
            'order_id'      => $order_id,
            'order_type'    => $mode,
            'cd'            => time(),
        ];
        try {
            $res = OrderSettlementMiddle::instance()->insert($insert);
            if( $res ) {
                return Normal::returnCode(Normal::SUC,"OK");
            }
            return Normal::returnCode(Normal::FAIL,"fail");
        } catch ( \Throwable $t) {
            return Normal::returnCode(Normal::FAIL,$t->getMessage());
        }
    }
    
    /**
     * 删除结算数据临时表
     * @param array $param
     */
    public function removeOrderSettleMentLog( $param = [] )
    {
        $orderInfo          = $param['supplierOrder'];
        $mode               = $param['mode'];
        $binfo              = $param['binfo'];
        $order_id           = $orderInfo['id'];
        OrderSettlementMiddle::instance()->where('bid',$binfo['bid'])->where('order_id',$order_id)->where('order_type',$mode)->delete();
        return Normal::returnCode(Normal::SUC,"fail");
    }
    
    /**
     * 推送结算服务数据
     * @param array $param
     */
    public function pushOrderSettleMentMessage( $param = [] ) 
    {
        $orderInfo          = $param['supplierOrder'];
        $orderGoods         = $param['orderGoods'];
        $companyInfo        = $param['companyInfo'];
        $mode               = $param['mode'];
        $binfo              = $param['binfo'];
        $currentGoods       = current($orderGoods);
        $total_costprice    = $user_taxAmount = $supplier_taxAmount = $total_price = $total_settlement_price = $total_delivery_money = 0 ;
        $goods = $goodsType = $userOrderGoodsSettleMentgData = $supplierOrderGoodsSettleMentData = [];
        foreach ($orderGoods as $v )
        {
            $goods[]                = "商品名:{$v['goods_name']},数量:{$v['quantity']},起售规格:{$v['spec_num']}";
            $goodsType[]            = $this->goodsType[$v['goods_type']]??"";
            $quantity               = $v['quantity'];
            $spec_num               = $v['spec_num'];
            $tax_rate               = $v['tax_rate'];
            $supplier_skucode       = $v['supplier_skucode'];
            $barcode                = $v['barcode'];
            $price                  = $v['price'];
            $costprice              = $v['costprice'];
            
            //供应商成本价    
            $total_costprice        = bcadd($total_costprice,bcmul($costprice, $quantity,2),2);
            
            //商户结算价
            $settlement_price       = $v['settlement_price'];
            $total_settlement_price = bcadd($total_settlement_price,bcmul($v['settlement_price'], $quantity,2),2);
            
            //商品销售总价
            $total_price            = bcadd($total_price,bcmul($price, $quantity,2),2);
            
            //税费 = 商品售价 * 税率
            $tax_rate_all           = bcadd($tax_rate,'1.0000',4);
            
            //商品不含税价格
            $noTaxPrice             = bcdiv($price, $tax_rate_all,2);
            $userTaxAmount          = bcsub($price, $noTaxPrice,2);
            $userTaxAmount          = bcmul($userTaxAmount, $quantity,2);
            $user_taxAmount         = bcadd($user_taxAmount,$userTaxAmount,2);
            
            //商户商品结算金额
            $userOrderGoodsSettleMentgData[] = [
                'commodityUniqueCode'   =>  $v['skucode'],
                'commodityName'         =>  $v['goods_name'],
                'goodsAmount'           =>  $price,
                'goodsCount'            =>  $quantity,
                "barCode"               =>  $barcode,
                "settlementAmount"      =>  $settlement_price,
                "specificationNum"      =>  $spec_num,
                "taxAmount"             =>  $userTaxAmount,
            ];
            //供应商商品成本价结算
            $supplierOrderGoodsSettleMentData[] = [
                'commodityUniqueCode'   =>  $v['supplier_skucode'],
                'commodityName'         =>  $v['goods_name'],
                'goodsAmount'           =>  $price,
                'goodsCount'            =>  $quantity,
                "barCode"               =>  $barcode,
                "settlementAmount"      =>  $costprice,
                "specificationNum"      =>  $spec_num,
                "taxAmount"             =>  $userTaxAmount
            ];
        }
        
        //商品名称
        $orderInfo['goods_contents'] = implode(";", $goods);
        //商品类型
        $orderInfo['goods_type_contents'] = implode(",", array_unique($goodsType));
        if( $mode == 1 && (($orderInfo['order_type'] == 0 && $orderInfo['after_sale_status'] = 1) || ($orderInfo['order_type'] > 0 && $orderInfo['after_verify_status'] = 1)) ) {
            $orderInfo['order_status_name'] = "已售后";
        } else {
            $orderInfo['order_status_name'] = "已支付";
        }
        
        //申报状态
        $orderInfo['apply_status_name'] = OrderSupplier::instance()->apply_status[$orderInfo['is_apply']]??"";
        //申报时间
        $orderInfo['apply_time']        = $orderInfo['apply_time'] ? date('Y-m-d H:i:s',$orderInfo['apply_time']) : '';
        //月份
        $orderInfo['month']             = date("Y年m月",$orderInfo['cd']);
        //订单日期
        $orderInfo['cd']                = date("Y-m-d H:i:s",$orderInfo['cd']);
        //订单类型
        $order_type                     = $orderInfo['order_type'] == 0 ? '其它':'云仓商城';
        //收货地址
        $receive_address                = implode("", [$orderInfo['province'],$orderInfo['city'],$orderInfo['district'],$orderInfo['receive_address']]);
        //渠道商结算金额 = 结算金额 + 税金（售价*税率）+ 运费
        $orderAmount                    = bcadd($total_settlement_price, $user_taxAmount,2);
        $total_delivery_money           = $orderInfo['total_template_delivery'];
        $orderAmount                    = bcadd($orderAmount,$total_delivery_money,2);
        //获取仓库信息
        $warehouse = WarehouseInfo::instance()->info(['ID'=>$currentGoods['store_id']]);
        $pushData = [];
        
        //C端真实付款金额
        $real_total_money = $orderInfo['real_total_money'];
        //C端优惠金额
        $discount_money   = $orderInfo['discount_money'];
        
        
        //商城支付成功之后订单进行渠道商结算
        if( $orderInfo['order_type'] != 1 ) {
            $pushData[] = [
                "orderDumpCode"    			=> $orderInfo['order_sn'],
                "orderDumpKey"     			=> $orderInfo['supplier_dsn'],
                "accountID"        			=> (string)$binfo['bid'],
                "linkAccountKey"   			=> (string)$companyInfo['company_name'],
                "orderDumpType"    			=> 1,
                "orderDumpMode"    			=> $mode,
                "settlementAmount" 			=> $orderAmount,
                "orderAmount"      			=> $real_total_money,
                "goodsAmount"      			=> $total_settlement_price,
                "discountAmount"   			=> $discount_money,
                "taxAmount"        			=> $user_taxAmount,
                "freightAmount"    			=> $total_delivery_money,
                "orderStatus"      			=> $orderInfo['order_status_name'],
                "declareStatus"    			=> $orderInfo['apply_status_name'],
                "orderTime"        			=> $orderInfo['cd'],
                "declareTime"      			=> $orderInfo['apply_time'],
                "deliveryMessage"  			=> "物流公司：{$orderInfo['express_name']},物流单号：{$orderInfo['express_sn']}",
                "recipient"        			=> $orderInfo['receive_name'],
                "recipientAddress" 			=> $receive_address,
                "telephone"        			=> $orderInfo['recveive_phone'],
                "deliveryWarehouse"			=> $warehouse['WarehouseName']??$companyInfo['company_name'],
                "declarant"        			=> $orderInfo['receive_name'],
                "declarantIDNum"   			=> $orderInfo['buyer_idcard'],
                "remark"           			=> $orderInfo['order_remark'],
                "orderSource"      			=> $order_type,
                "deliveryCode"     			=> $orderInfo['express_sn'],
                "deliveryMode"     			=> $orderInfo['express_name'],
                "deliveryTime"     			=> $orderInfo['express_shipping_time'] ? date('Y-m-d H:i:s',$orderInfo['express_shipping_time']) : '',
                "tradeType"        			=> $orderInfo['goods_type_contents'],
                "tempOrderGoodsDumpInfos" 	=> $userOrderGoodsSettleMentgData
            ];
        }
        
        //供应商结算金额 = 结算金额 + 税金（售价*税率）+ 运费
        $suppplierOrderAmount           = bcadd($total_costprice, $user_taxAmount,2);
        $suppplierTotalDeliveryMoney    = 0.00;
        $suppplierOrderAmount           = bcadd($suppplierOrderAmount,$suppplierTotalDeliveryMoney,2);
        
        //供应商结算数据
        $pushData[] = [
            "orderDumpCode"     		=> $orderInfo['order_sn'],
            "orderDumpKey"      		=> $orderInfo['supplier_dsn'],
            "accountID"         		=> (string)$orderInfo['company_id'],
            "linkAccountKey"    		=> (string)$binfo['name'],
            "orderDumpType"     		=> 0,
            "orderDumpMode"     		=> $mode,
            "settlementAmount"  		=> $suppplierOrderAmount,
            "orderAmount"       		=> $real_total_money,
            "goodsAmount"       		=> $total_costprice,
            "discountAmount"    		=> $discount_money,
            "taxAmount"         		=> $user_taxAmount,
            "orderStatus"       		=> $orderInfo['order_status_name'],
            "declareStatus"     		=> $orderInfo['apply_status_name'],
            "orderTime"         		=> $orderInfo['cd'],
            "declareTime"       		=> $orderInfo['apply_time'],
            "deliveryMessage"   		=> "物流公司：{$orderInfo['express_name']},物流单号：{$orderInfo['express_sn']}",
            "recipient"         		=> $orderInfo['receive_name'],
            "recipientAddress"  		=> $receive_address,
            "telephone"         		=> $orderInfo['recveive_phone'],
            "deliveryWarehouse" 		=> $warehouse['WarehouseName']??$companyInfo['company_name'],
            "declarant"         		=> $orderInfo['receive_name'],
            "declarantIDNum"    		=> $orderInfo['buyer_idcard'],
            "remark"            		=> $orderInfo['order_remark'],
            "orderSource"       		=> $order_type,
            "deliveryCode"      		=> $orderInfo['express_sn'],
            "deliveryMode"      		=> $orderInfo['express_name'],
            "deliveryTime"      		=> $orderInfo['express_shipping_time'] ? date('Y-m-d H:i:s',$orderInfo['express_shipping_time']) : '',
            "tradeType"         		=> $orderInfo['goods_type_contents'],
            "tempOrderGoodsDumpInfos" 	=> $supplierOrderGoodsSettleMentData
        ];
                
        $MessageType = $mode == 1 ? 'orderAfterSettleMentService' : 'orderSettleMentService';
        
        //将数据包发送到消息队列
        $contents = [
            'MessageType' => $MessageType,
            'Message'     => [
                'tempOrderDumpInfos' => $pushData,
                'systemID' => config('gateway_net.systemInfoID'),
            ]
        ];
        $contents['Message']    = json_encode($contents['Message'],JSON_UNESCAPED_UNICODE);
        $contents['Sign']       = md5($contents['MessageType'].$contents['Message']);
        $publishMsg             = json_encode($contents);
        
        try {
            $message = new HglycSettleMentProducer($contents);
            $producer = ApplicationContext::getContainer()->get(Producer::class);
            $producer->produce($message);
            logger('info','HglycSettleMentProducer')->info($publishMsg);
            return Normal::returnCode(Normal::SUC,"发布成功");
        } catch ( Throwable $e ) {
            logger('info','rmq-error')->info($e->getMessage());
            return Normal::returnCode(Normal::FAIL,$e->getMessage());
        }
    }
}